package ch12.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MyFileReader {
	/**
	 * 把一段文本内容写入到一个指定文件中
	 * 
	 * @param fileName
	 * @param content
	 */
	public void writeFile(String fileName, String content) {
		if (fileName == null) {
			return;
		}
		File file = new File(fileName);
		FileOutputStream outputStream = null;
		try {
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			outputStream = new FileOutputStream(file,false);//文件的写入有两种模式，重写，追加
			outputStream.write(content.getBytes());//需要把字符串转换成字节数字，转换时需要注意可能产生乱码
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(outputStream!=null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
	
	/**
	 * 拷贝文件，并把小写l全部修改为大小L
	 * 
	 * @param src
	 * @param desc
	 */
	public void copyAndFilter(String src, String desc) {
		if (src == null || desc == null) {
			return;
		}
		File srcFile = new File(src);
		File descFile = new File(desc);

		if (!srcFile.exists()) {
			return;
		}

		FileReader reader  = null;
		FileWriter writer = null;
		BufferedReader bufferedReader = null;
		try {
			if (!descFile.exists()) {
				descFile.getParentFile().mkdirs();
				descFile.createNewFile();
			}
			reader= new FileReader(srcFile);//节点流
			bufferedReader = new BufferedReader(reader);//处理流
			writer = new FileWriter(descFile);//节点流
			String data = null;
			//readLine一次读取一行内容，文件读取完毕返回null
			while((data=bufferedReader.readLine())!=null) {
		         String newData = data.replaceAll("l", "L");
		         writer.write(newData);
			}	
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(writer!=null) {
				try {
					writer.close();
				} catch (IOException e) {
				}
			}
			if(bufferedReader!=null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
				}
			}
			if(reader!=null) {
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
		}

	}

	public static void main(String[] args) {
		MyFileReader fileReader = new MyFileReader();
		fileReader.writeFile("c:/test.txt", "hello world");
		System.out.println("文件新增成功");
		
		fileReader.copyAndFilter("c:/test.txt", "c:/test2.txt");

	}

}
